package gov.fema.hazus.bdc.server.servlet.tasks;

import gov.fema.hazus.bdc.server.servlet.DAO;
import gov.fema.hazus.bdc.shared.entity.AEBMResults;
import gov.fema.hazus.bdc.shared.entity.Address;
import gov.fema.hazus.bdc.shared.entity.Bracing;
import gov.fema.hazus.bdc.shared.entity.Building;
import gov.fema.hazus.bdc.shared.entity.Capacity;
import gov.fema.hazus.bdc.shared.entity.Contact;
import gov.fema.hazus.bdc.shared.entity.EarthquakeBuildingDesign;
import gov.fema.hazus.bdc.shared.entity.EarthquakeHazard;
import gov.fema.hazus.bdc.shared.entity.EarthquakeSecondaryCharacteristics;
import gov.fema.hazus.bdc.shared.entity.Economy;
import gov.fema.hazus.bdc.shared.entity.FloodBasement;
import gov.fema.hazus.bdc.shared.entity.FloodBuildingDesign;
import gov.fema.hazus.bdc.shared.entity.FloodHazard;
import gov.fema.hazus.bdc.shared.entity.Location;
import gov.fema.hazus.bdc.shared.entity.ManufacturedHousing;
import gov.fema.hazus.bdc.shared.entity.Roof;
import gov.fema.hazus.bdc.shared.entity.WallsAndOpenings;
import gov.fema.hazus.bdc.shared.entity.WindBuildingDesign;
import gov.fema.hazus.bdc.shared.entity.WindHazard;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Scanner;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.appengine.api.labs.taskqueue.TaskOptions.Method;
import com.google.inject.Singleton;

@Singleton
public class TaskQueueLoadBuildingsObjectify extends HttpServlet {

	public static final String TASK_PATH = "/task/objectify/buildings/load";

	private final Logger logger = Logger.getLogger(TaskQueueLoadBuildingsObjectify.class);
    private Cache cache;

    private DAO dao = new DAO();
    
    public void init(ServletConfig config) throws ServletException {

        // Store the ServletConfig object and log the initialization
        super.init(config);
        logger.debug("Initializing servlet");
        
        try {
        	logger.debug("Initializing cache");
        	cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
            logger.debug("Could not setup cache");
        }
        
    }
    
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	 throws ServletException, IOException {
		
		String lineNum = req.getParameter("l");
		int index = Integer.parseInt(lineNum);
		logger.debug("Parse index:" + index);
		
		ArrayList<String> out = (ArrayList<String>) cache.get("csv");
		logger.debug("Index ("+index+") from out=" + out.get(index));
		
		String line = out.get(index);
		String[] parts = line.split(",");
		
		try {
			
			Building building = new Building();
			
			String number = parseFieldAsString(parts[0]);
			String name = parseFieldAsString(parts[25]);
			
			building.setName(name);
			
			ArrayList<String> terms = new ArrayList<String>();
			logger.debug(name);
			name = name.replaceAll("[^a-zA-Z 0-9]", " ");
			name = name.replaceAll("\\s+ ", " ");
			logger.debug(name);
			name = name.toUpperCase();
			logger.debug(name);
			String[] words = name.split(" ");	
			for (int i = 0; i < words.length; i++) {
				logger.debug(words[i]);
				String term = words[i];
				// add term to terms
				terms.add(term);
			}
			logger.debug(terms);
			building.setTerms(terms);
			building.setNumber(number);
			building.setMode(Building.EDITABLE);
			String occupancy = parseFieldAsString(parts[39]);
			String buildingType = parseFieldAsString(parts[40]);
			Integer area = parseFieldAsInteger(parts[41]);
			Integer constructionYear = parseFieldAsInteger(parts[42]);
			Integer stories = parseFieldAsInteger(parts[43]);
			building.setOccupancy(occupancy);
			building.setBuildingType(buildingType);
			building.setArea(area);
			building.setConstructionYear(constructionYear);
			building.setStories(stories);
			//building.setUserName(userName);
			//building.setMode(mode);
			dao.ofy().put(building);
			
			Address address = new Address();
			String street1 = parseFieldAsString(parts[26]);
			String city = parseFieldAsString(parts[27]);
			String state = parseFieldAsString(parts[28]);
			String zipCode = parseFieldAsString(parts[29]);
			address.setId(building.getId());
			address.setStreet1(street1);
			address.setCity(city);
			address.setState(state);
			address.setPostalCode(zipCode);
			dao.ofy().put(address);
			
			Location location = new Location();
			location.setId(building.getId());
			Double latitude = parseFieldAsDouble(parts[33]);
			Double longitude = parseFieldAsDouble(parts[34]);
			String censusBlock = parseFieldAsString(parts[35]);
			String censusGroup = parseFieldAsString(parts[36]);
			String censusTract = parseFieldAsString(parts[37]);
			String countyFIPS = parseFieldAsString(parts[38]);
			location.setLatitude(latitude);
			location.setLongitude(longitude);
			location.setCensusBlock(censusBlock);
			location.setCensusGroup(censusGroup);
			location.setCensusTract(censusTract);
			location.setCountyFIPS(countyFIPS);
			dao.ofy().put(location);
			
			Contact contact = new Contact();
			contact.setId(building.getId());
			String owner = parseFieldAsString(parts[30]);
			String contactPerson = parseFieldAsString(parts[31]);
			String phone = parseFieldAsString(parts[32]);
			contact.setOwner(owner);
			contact.setContactPerson(contactPerson);
			contact.setPhone(phone);
			dao.ofy().put(contact);
			
			Economy economy = new Economy();
			economy.setId(building.getId());
			Double buildingValue = parseFieldAsDouble(parts[44]);
			String valuationType = parseFieldAsString(parts[45]);
			Integer valuationYear = parseFieldAsInteger(parts[46]);
			Double contentsValue = parseFieldAsDouble(parts[47]);
			Double rentalIncomePerMonth = parseFieldAsDouble(parts[48]);
			Double inventoryValue = parseFieldAsDouble(parts[49]);
			Double businessIncomePerDay = parseFieldAsDouble(parts[50]);
			Double wagesPerDay = parseFieldAsDouble(parts[51]);
			economy.setBuildingValue(buildingValue);
			economy.setValuationType(valuationType);
			economy.setValuationYear(valuationYear);
			economy.setContentsValue(contentsValue);
			economy.setInventoryValue(inventoryValue);
			economy.setRentalIncomePerMonth(rentalIncomePerMonth);
			economy.setBusinessIncomePerDay(businessIncomePerDay);
			economy.setWagesPerDay(wagesPerDay);
			dao.ofy().put(economy);

			Capacity capacity = new Capacity();
			capacity.setId(building.getId());
			Integer daytimeOccupants = parseFieldAsInteger(parts[52]);
			Integer nighttimeOccupants = parseFieldAsInteger(parts[53]);
			String kitchen = parseFieldAsString(parts[54]);
			Integer kitchenCapacity = parseFieldAsInteger(parts[55]);
			String dining = parseFieldAsString(parts[56]);
			Integer diningCapacity = parseFieldAsInteger(parts[57]);
			String sleeping = parseFieldAsString(parts[58]);
			Integer sleepingCapacity = parseFieldAsInteger(parts[59]);
			Integer hospitalBeds = parseFieldAsInteger(parts[60]);
			Integer vehicles = parseFieldAsInteger(parts[61]);
			String hazardousMaterials = parseFieldAsString(parts[62]);
			capacity.setDaytimeOccupants(daytimeOccupants);
			capacity.setNighttimeOccupants(nighttimeOccupants);
			capacity.setKitchen(kitchen);
			capacity.setKitchenCapacity(kitchenCapacity);
			capacity.setDining(dining);
			capacity.setDiningCapacity(diningCapacity);
			capacity.setSleeping(sleeping);
			capacity.setSleepingCapacity(sleepingCapacity);
			capacity.setHospitalBeds(hospitalBeds);
			capacity.setVehicles(vehicles);
			capacity.setHazardousMaterials(hazardousMaterials);
			dao.ofy().put(capacity);

			// eq
			Bracing bracing = new Bracing();
			bracing.setId(building.getId());
			String crippleWalls = parseFieldAsString(parts[82]);
			String chimneyAnchored = parseFieldAsString(parts[83]);
			String plumbingSystem = parseFieldAsString(parts[84]);
			String mechanicalSystem = parseFieldAsString(parts[85]);
			String electricalSystem = parseFieldAsString(parts[86]);
			String suspendedCeiling = parseFieldAsString(parts[87]);
			String mechanicalOnRoof = parseFieldAsString(parts[88]);
			String rooftanks = parseFieldAsString(parts[89]);
			bracing.setCrippleWalls(crippleWalls);
			bracing.setChimneyAnchored(chimneyAnchored);
			bracing.setPlumbingSystem(plumbingSystem);
			bracing.setMechanicalSystem(mechanicalSystem);
			bracing.setElectricalSystem(electricalSystem);
			bracing.setSuspendedCeiling(suspendedCeiling);
			bracing.setMechanicalOnRoof(mechanicalOnRoof);
			bracing.setRooftanks(rooftanks);
			dao.ofy().put(bracing);
			
			EarthquakeHazard earthquakehazard = new EarthquakeHazard();
			earthquakehazard.setId(building.getId());
			String soilType = parseFieldAsString(parts[63]);
			String landslideSusceptibility = parseFieldAsString(parts[64]);
			String liquefactionSusceptibility = parseFieldAsString(parts[65]);
			Integer groundwaterDepth = parseFieldAsInteger(parts[66]);
			earthquakehazard.setSoilType(soilType);
			earthquakehazard.setLandslideSusceptibility(landslideSusceptibility);
			earthquakehazard.setLiquefactionSusceptibility(liquefactionSusceptibility);
			earthquakehazard.setGroundwaterDepth(groundwaterDepth);
			dao.ofy().put(earthquakehazard);

			EarthquakeBuildingDesign earthquakebuildingdesign = new EarthquakeBuildingDesign();
			earthquakebuildingdesign.setId(building.getId());
			String designCode = parseFieldAsString(parts[67]);
			String designLevel = parseFieldAsString(parts[68]);
			Integer designYear = parseFieldAsInteger(parts[69]);
			Double designBaseShear = parseFieldAsDouble(parts[70]);
			String foundationType = parseFieldAsString(parts[71]);
			String constructionQuality = parseFieldAsString(parts[72]);
			Integer percentageContentsOnGround = parseFieldAsInteger(parts[73]);
			earthquakebuildingdesign.setDesignCode(designCode);
			earthquakebuildingdesign.setDesignLevel(designLevel);
			earthquakebuildingdesign.setDesignYear(designYear);
			earthquakebuildingdesign.setDesignBaseShear(designBaseShear);
			earthquakebuildingdesign.setFoundationType(foundationType);
			earthquakebuildingdesign.setConstructionQuality(constructionQuality);
			earthquakebuildingdesign.setPercentageContentsOnGround(percentageContentsOnGround);
			dao.ofy().put(earthquakebuildingdesign);
			
			EarthquakeSecondaryCharacteristics earthquakesecondarycharacteristics = new EarthquakeSecondaryCharacteristics();
			earthquakesecondarycharacteristics.setId(building.getId());
			String horizontalShape = parseFieldAsString(parts[74]);
			String verticalShape = parseFieldAsString(parts[75]);
			String torsion = parseFieldAsString(parts[76]);
			String softStory = parseFieldAsString(parts[77]);
			String shortColumns = parseFieldAsString(parts[78]);
			String pounding = parseFieldAsString(parts[79]);
			String URMRetrofit = parseFieldAsString(parts[80]);
			String ornamentation = parseFieldAsString(parts[81]);
			earthquakesecondarycharacteristics.setHorizontalShape(horizontalShape);
			earthquakesecondarycharacteristics.setVerticalShape(verticalShape);
			earthquakesecondarycharacteristics.setTorsion(torsion);
			earthquakesecondarycharacteristics.setSoftStory(softStory);
			earthquakesecondarycharacteristics.setShortColumns(shortColumns);
			earthquakesecondarycharacteristics.setPounding(pounding);
			earthquakesecondarycharacteristics.setURMRetrofit(URMRetrofit);
			earthquakesecondarycharacteristics.setOrnamentation(ornamentation);
			dao.ofy().put(earthquakesecondarycharacteristics);

			// fl
			FloodBasement floodbasement = new FloodBasement();
			floodbasement.setId(building.getId());
			Double levels = parseFieldAsDouble(parts[108]);
			Double percentageContentsValue = parseFieldAsDouble(parts[109]);
			Double percentageFinished = parseFieldAsDouble(parts[110]);
			String dryFloodProofed = parseFieldAsString(parts[111]);
			Integer floodProofingElevation = parseFieldAsInteger(parts[112]);
			String enclosureType = parseFieldAsString(parts[113]);
			floodbasement.setLevels(levels);
			floodbasement.setPercentageContentsValue(percentageContentsValue);
			floodbasement.setPercentageFinished(percentageFinished);
			floodbasement.setDryFloodProofed(dryFloodProofed);
			floodbasement.setFloodProofingElevation(floodProofingElevation);
			floodbasement.setEnclosureType(enclosureType);
			dao.ofy().put(floodbasement);
			
			FloodBuildingDesign floodbuildingdesign = new FloodBuildingDesign();
			floodbuildingdesign.setId(building.getId());
			String postFIRMConstruction = parseFieldAsString(parts[100]);
			String constructionClass = parseFieldAsString(parts[101]);
			String buildingCondition = parseFieldAsString(parts[102]);
			String substructureType = parseFieldAsString(parts[103]);
			Integer lowestFloorElevation = parseFieldAsInteger(parts[104]);
			String topBottomFloor = parseFieldAsString(parts[105]);
			String lowestFloorBelowGrade = parseFieldAsString(parts[106]);
			Integer mechanicalEquipmentHeight = parseFieldAsInteger(parts[107]);
			floodbuildingdesign.setPostFIRMConstruction(postFIRMConstruction);
			floodbuildingdesign.setConstructionClass(constructionClass);
			floodbuildingdesign.setBuildingCondition(buildingCondition);
			floodbuildingdesign.setSubstructureType(substructureType);
			floodbuildingdesign.setLowestFloorElevation(lowestFloorElevation);
			floodbuildingdesign.setTopBottomFloor(topBottomFloor);
			floodbuildingdesign.setLowestFloorBelowGrade(lowestFloorBelowGrade);
			floodbuildingdesign.setMechanicalEquipmentHeight(mechanicalEquipmentHeight);
			dao.ofy().put(floodbuildingdesign);
			
			FloodHazard floodhazard = new FloodHazard();
			floodhazard.setId(building.getId());
			String FIRMPanel = parseFieldAsString(parts[90]);
			String FIRMCommunity = parseFieldAsString(parts[91]);
			Date FIRMEffectiveDate = parseFieldAsDate(parts[92]);
			Date FIRMRevisedDate = parseFieldAsDate(parts[93]);
			String floodHazardZone = parseFieldAsString(parts[94]);
			Integer baseFloodElevation = parseFieldAsInteger(parts[95]);
			String verticalDatum = parseFieldAsString(parts[96]);
			String otherVerticalDatum = parseFieldAsString(parts[97]);
			Integer baseFloodElevationPlus = parseFieldAsInteger(parts[98]);
			Integer lowestGradeElevation = parseFieldAsInteger(parts[99]);
			floodhazard.setFIRMPanel(FIRMPanel);
			floodhazard.setFIRMCommunity(FIRMCommunity);
			floodhazard.setFIRMEffectiveDate(FIRMEffectiveDate);
			floodhazard.setFIRMRevisedDate(FIRMRevisedDate);
			floodhazard.setFloodHazardZone(floodHazardZone);
			floodhazard.setBaseFloodElevation(baseFloodElevation);
			floodhazard.setVerticalDatum(verticalDatum);
			floodhazard.setOtherVerticalDatum(otherVerticalDatum);
			floodhazard.setBaseFloodElevationPlus(baseFloodElevationPlus);
			floodhazard.setLowestGradeElevation(lowestGradeElevation);
			dao.ofy().put(floodhazard);
			
			
			// wind
			ManufacturedHousing manufacturedhousing = new ManufacturedHousing();
			manufacturedhousing.setId(building.getId());
			String housingCode = parseFieldAsString(parts[146]);
			String windZone = parseFieldAsString(parts[147]);
			String tieDowns = parseFieldAsString(parts[148]);
			manufacturedhousing.setTieDowns(tieDowns);
			manufacturedhousing.setHousingCode(housingCode);
			manufacturedhousing.setWindZone(windZone);
			dao.ofy().put(manufacturedhousing);
			
			Roof roof = new Roof();
			roof.setId(building.getId());
			String slope = parseFieldAsString(parts[123]);
			String covering = parseFieldAsString(parts[124]);
			String shape = parseFieldAsString(parts[125]);
			String gableEndBracing = parseFieldAsString(parts[126]);
			String sheathing = parseFieldAsString(parts[127]);
			String nailSize = parseFieldAsString(parts[128]);
			String nailSpacing = parseFieldAsString(parts[129]);
			String deckAttachment = parseFieldAsString(parts[130]);
			String frameSpacing = parseFieldAsString(parts[131]);
			String roofWallAnchorage = parseFieldAsString(parts[132]);
			String roofPerimeter = parseFieldAsString(parts[133]);
			roof.setSlope(slope);
			roof.setCovering(covering);
			roof.setShape(shape);
			roof.setGableEndBracing(gableEndBracing);
			roof.setSheathing(sheathing);
			roof.setNailSize(nailSize);
			roof.setNailSpacing(nailSpacing);
			roof.setDeckAttachment(deckAttachment);
			roof.setFrameSpacing(frameSpacing);
			roof.setRoofWallAnchorage(roofWallAnchorage);
			roof.setRoofPerimeter(roofPerimeter);
			dao.ofy().put(roof);

			WallsAndOpenings wallsandopenings = new WallsAndOpenings();
			wallsandopenings.setId(building.getId());
			String cladding = parseFieldAsString(parts[134]);
			Integer maximumExposure = parseFieldAsInteger(parts[135]);
			String percentageDoorWindowOpenings = parseFieldAsString(parts[136]);
			String glassType = parseFieldAsString(parts[137]);
			String glassPaneConstruction = parseFieldAsString(parts[138]);
			String shutterType = parseFieldAsString(parts[139]);
			String shutterCompliance = parseFieldAsString(parts[140]);
			String percentageOtherDoorArea = parseFieldAsString(parts[141]);
			String garageDoors = parseFieldAsString(parts[142]);
			String rollUpDoors = parseFieldAsString(parts[143]);
			String doorProtectionType = parseFieldAsString(parts[144]);
			String doorProtectionCompliance = parseFieldAsString(parts[145]);
			wallsandopenings.setCladding(cladding);
			wallsandopenings.setMaximumExposure(maximumExposure);
			wallsandopenings.setPercentageDoorWindowOpenings(percentageDoorWindowOpenings);
			wallsandopenings.setGlassType(glassType);
			wallsandopenings.setGlassPaneConstruction(glassPaneConstruction);
			wallsandopenings.setShutterType(shutterType);
			wallsandopenings.setShutterCompliance(shutterCompliance);
			wallsandopenings.setPercentageOtherDoorArea(percentageOtherDoorArea);
			wallsandopenings.setGarageDoors(garageDoors);
			wallsandopenings.setRollUpDoors(rollUpDoors);
			wallsandopenings.setDoorProtectionType(doorProtectionType);
			wallsandopenings.setDoorProtectionCompliance(doorProtectionCompliance);
			dao.ofy().put(wallsandopenings);

			WindBuildingDesign windbuildingdesign = new WindBuildingDesign();
			windbuildingdesign.setId(building.getId());
			Integer designWindSpeed = parseFieldAsInteger(parts[119]);
			String windSpeedType = parseFieldAsString(parts[120]);
			String windDesignCode = parseFieldAsString(parts[121]);
			Integer windDesignYear = parseFieldAsInteger(parts[122]);
			windbuildingdesign.setDesignCode(windDesignCode);
			windbuildingdesign.setDesignYear(windDesignYear);
			windbuildingdesign.setDesignWindSpeed(designWindSpeed);
			windbuildingdesign.setWindSpeedType(windSpeedType);
			dao.ofy().put(windbuildingdesign);
			
			WindHazard windhazard = new WindHazard();
			windhazard.setId(building.getId());
			String exposure = parseFieldAsString(parts[114]);
			String topography = parseFieldAsString(parts[115]);
			String shielding = parseFieldAsString(parts[116]);
			String shieldingHeight = parseFieldAsString(parts[117]);
			String debrisSource = parseFieldAsString(parts[118]);
			windhazard.setExposure(exposure);
			windhazard.setTopography(topography);
			windhazard.setShielding(shielding);
			windhazard.setShieldingHeight(shieldingHeight);
			windhazard.setDebrisSource(debrisSource);
			dao.ofy().put(windhazard);

			AEBMResults aebmResults = new AEBMResults();
			aebmResults.setId(building.getId());
			Double strDsNone = parseFieldAsDouble(parts[1]);
			Double strDsSlight = parseFieldAsDouble(parts[2]);
			Double strDsModerate = parseFieldAsDouble(parts[3]);
			Double strDsExtensive = parseFieldAsDouble(parts[4]);
			Double strDsComplete = parseFieldAsDouble(parts[5]);
			Double nonStrDsNone = parseFieldAsDouble(parts[6]);
			Double nonStrDsSlight = parseFieldAsDouble(parts[7]);
			Double nonStrDsModerate = parseFieldAsDouble(parts[8]);
			Double nonStrDsExtensive = parseFieldAsDouble(parts[9]);
			Double nonStrDsComplete = parseFieldAsDouble(parts[10]);
			//String casDayALL = parseFieldAsString(parts[11]);
			Double casDayLevel1 = parseFieldAsDouble(parts[12]);
			Double casDayLevel2 = parseFieldAsDouble(parts[13]);
			Double casDayLevel3 = parseFieldAsDouble(parts[14]);
			Double casDayLevel4 = parseFieldAsDouble(parts[15]);
			Double casNightLevel1 = parseFieldAsDouble(parts[16]);
			Double casNightLevel2 = parseFieldAsDouble(parts[17]);
			Double casNightLevel3 = parseFieldAsDouble(parts[18]);
			Double casNightLevel4 = parseFieldAsDouble(parts[19]);
			Double lossStructural = parseFieldAsDouble(parts[20]);
			Double lossNonStructural = parseFieldAsDouble(parts[21]);
			Double lossContents = parseFieldAsDouble(parts[22]);
			Double lossBusinessRelated = parseFieldAsDouble(parts[23]);
			Double lossTotalEconomicLoss = parseFieldAsDouble(parts[24]);
			aebmResults.setNumber(number);
			aebmResults.setRequiresMedicalAttentionDaytime(casDayLevel1);
			aebmResults.setRequiresHospitalizationDaytime(casDayLevel2);
			aebmResults.setLifeThreateningInjuriesDaytime(casDayLevel3);
			aebmResults.setDeathsDaytime(casDayLevel4);
			aebmResults.setRequiresMedicalAttentionNighttime(casNightLevel1);
			aebmResults.setRequiresHospitalizationNighttime(casNightLevel2);
			aebmResults.setLifeThreateningInjuriesNighttime(casNightLevel3);
			aebmResults.setDeathsNighttime(casNightLevel4);
			aebmResults.setStructuralPercentDamageNone(strDsNone);
			aebmResults.setStructuralPercentDamageSlight(strDsSlight);
			aebmResults.setStructuralPercentDamageModerate(strDsModerate);
			aebmResults.setStructuralPercentDamageExtensive(strDsExtensive);
			aebmResults.setStructuralPercentDamageComplete(strDsComplete);
			aebmResults.setNonStructuralPercentDamageNone(nonStrDsNone);
			aebmResults.setNonStructuralPercentDamageSlight(nonStrDsSlight);
			aebmResults.setNonStructuralPercentDamageModerate(nonStrDsModerate);
			aebmResults.setNonStructuralPercentDamageExtensive(nonStrDsExtensive);
			aebmResults.setNonStructuralPercentDamageComplete(nonStrDsComplete);
			aebmResults.setStructuralLoss(lossStructural);
			aebmResults.setNonStructuralLoss(lossNonStructural);
			aebmResults.setContentsLoss(lossContents);
			aebmResults.setBusinessIncomeLoss(lossBusinessRelated);
			aebmResults.setTotalEconomicLoss(lossTotalEconomicLoss);
			aebmResults.setDaytimeOccupants(daytimeOccupants);
			aebmResults.setNighttimeOccupants(nighttimeOccupants);
			aebmResults.setContentsValue(contentsValue);
			aebmResults.setBusinessRelatedLoss(lossBusinessRelated);
			
	        //building.setAddress(address);
			dao.ofy().put(aebmResults);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	 }
	
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException {
        
    	res.setContentType("text/plain");

    	/*
    	 * Load the CSV, store as array of strings in the cache, queue the processor
    	 */
    	res.getWriter().println("Loading all.csv");
    	String dataPath = "WEB-INF/data/all.csv";
    	File file = new File(dataPath);
		Scanner scanner = new Scanner(file);
		scanner.nextLine(); // always skip first line of headers
		ArrayList<String> data = new ArrayList<String>();
		while(scanner.hasNextLine())
		{
			String line = scanner.nextLine();
			logger.debug(line);
			data.add(line);
		}
		
		
		// Store the list in cache
		res.getWriter().println("Preparing cache");
		
        res.getWriter().println("Storing CSV data");
        cache.put("csv", data);

        // test, get it out again
        res.getWriter().println("Fetching CSV data");
        ArrayList<String> out = (ArrayList<String>) cache.get("csv");
        res.getWriter().println("fetched data size=" + out.size());

    	for (int i = 0; i < data.size(); i++) {
    		String taskNotice = "Create task for row("+i+")";
    		res.getWriter().println(taskNotice);
    		logger.debug(taskNotice);
    		Queue queue = QueueFactory.getQueue("load-buildings");
    		queue.add(TaskOptions.Builder.url(TASK_PATH).method(Method.POST).param("l",Integer.toString(i)));
		}
    	
    	
    }
    
	private Double parseFieldAsDouble(String value)
	{
		Double doubleValue = null;
		try {
			doubleValue = Double.parseDouble(value);
		} catch (Exception e)
		{
			logger.debug(" ("+value+") was not parsed as Double, returning null");
		}
		return doubleValue;
	}
	
	private Integer parseFieldAsInteger(String value)
	{
		Integer integerValue = null;
		try {
			integerValue = Integer.parseInt(value);
		} catch (Exception e)
		{
			logger.debug(" ("+value+") was not parsed as Integer, returning null");
		}
		return integerValue;
	}
	
	private Date parseFieldAsDate(String value)
	{
		Date dateValue = null;
		try {
			dateValue = new Date(value);
		} catch (Exception e)
		{
			logger.debug(" ("+value+") was not parsed as Date, returning null");
		}
		return dateValue;
	}
	
	private String parseFieldAsString(String value)
	{
		return value;
	}	
}
